package demo15;

import java.util.*;

/**
 * 综合练习_全排列II
 * https://leetcode.cn/problems/7p8L0Z/description/
 */
class Solution {
    List<List<Integer>> ret = new ArrayList<>();
    List<Integer> path = new ArrayList<>();
    boolean[] check;
    int len;
    public List<List<Integer>> permuteUnique(int[] nums) {
        len = nums.length;
        check = new boolean[len];
        Arrays.sort(nums);
        dfs(nums);
        return ret;
    }

    private void dfs(int[] nums) {
        if(len == path.size() ) {
            ret.add(new ArrayList<>(path));
            return;
        }
        for(int i = 0; i < len; i++) {
            if(!check[i] && (i == 0 || nums[i] != nums[i-1] || check[i - 1])) {
                path.add(nums[i]);
                check[i] = true;
                dfs(nums);
                // 恢复现场
                path.remove(path.size() -1);
                check[i] = false;
            }
        }
    }
}
class Demo {
    public static void main(String[] args) {
        Solution solution = new Solution();
        List<List<Integer>> list = solution.permuteUnique(new int[]{1, 1, 2});
        for(List<Integer> ls : list) {
            for(Integer l : ls) {
                System.out.print(l + " ");
            }
            System.out.println();
        }
    }
}